package com.enjia.common.view;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ProgressBar;

import com.enjia.enjiashop.R;


/**
 * Created by 张海洋 on 2017-08-21.
 */

public class ProgressWebView extends WebView {
    protected String showTitle;
    private ProgressBar progressBar;

    public ProgressWebView(Context context) {
        this(context,null);
    }

    public ProgressWebView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ProgressWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    private void init(Context context, AttributeSet attrs, int defStyleAttr) {
        progressBar = new ProgressBar(context,null,android.R.attr.progressBarStyleHorizontal);
        progressBar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,10,0,0));
        Drawable drawable = context.getResources().getDrawable(R.drawable.progress_bar_states);
        progressBar.setProgressDrawable(drawable);
        addView(progressBar);

        setWebChromeClient(new WebChromeClient1());

        // 是否可以缩放
        /*WebSettings settings = getSettings();
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(true);*/
    }

    public class WebChromeClient1 extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressBar.setVisibility(GONE);
            } else {
                if (progressBar.getVisibility() == GONE)
                    progressBar.setVisibility(VISIBLE);
                progressBar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            showTitle = title;
        }
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        LayoutParams layoutParams = (LayoutParams) progressBar.getLayoutParams();
        layoutParams.x = l;
        layoutParams.y = t;
        progressBar.setLayoutParams(layoutParams);

        super.onScrollChanged(l, t, oldl, oldt);
    }
}
